﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Jose;
namespace FrameWorkCore.JWT
{
    public class JWTAuthService: IJWTAuthService
    {

        public IConfiguration Configuration { get; set; }


        /// <summary>
        /// Access token
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string GetAuthToken(string SubjectId)
        {

            var claims = new List<Claim>()
            {
                new Claim("SubjectId",SubjectId)
            };

            var now = DateTime.UtcNow;
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: Configuration.GetValue<string>("JWT:ValidIssuer"),
                audience: Configuration.GetValue<string>("JWT:ValidAudience"),
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMinutes(Configuration.GetValue<int>("JWT:expiresMinutes"))),
                signingCredentials: new SigningCredentials
                (
                    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JWT:SecurityKey"))),
                    SecurityAlgorithms.HmacSha256
                )
            );

            return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        }

        /// <summary>
        /// Decrypt the token
        /// </summary>
        /// <param name="DecryptToken"></param>
        /// <returns></returns>
        public object GetSerializableToken(string DecryptToken)
        {
            string tokenstr = Jose.JWT.Decode(
                  DecryptToken,
                  Encoding.ASCII.GetBytes(Configuration.GetValue<string>("JWT:SecurityKey")),
                  JweAlgorithm.PBES2_HS256_A128KW,
                  JweEncryption.A128CBC_HS256,     
                  null
              );
    
            return tokenstr;

        }
    }

    public interface IJWTAuthService
    {
        public string GetAuthToken(string SubjectId);

        public object GetSerializableToken(string DecryptToken);

    }
}
